package top.jfunc.common.router;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询选择
 */
public class RoundRobinRouter<T,O> implements Router<T,O> {
    private static long CACHE_VALID_TIME = 0;

    private AtomicInteger count;

    @Override
    public T select(List<T> toSelectedList, O otherParam) {
        return toSelectedList.get(count(toSelectedList.size()));
    }

    /**
     * 轮询最大不超过max的值
     */
    private int count(int max) {
        // 缓存一天后清除，重新计算
        if (System.currentTimeMillis() > CACHE_VALID_TIME) {
            CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24;
            //第一次随机
            count = new AtomicInteger(new Random().nextInt(max));
        }

        //防止溢出
        return count.addAndGet(1) % max;
    }
}
